import datetime
import logging
from patch_tracking.util.gitee_api import get_repo, get_branch, get_yaml_content
from patch_tracking.util.github_api import GitHubApi
from patch_tracking.database.models import Tracking
from patch_tracking.api.business import create_tracking, update_tracking
from patch_tracking.task import scheduler
from patch_tracking.settings import TRACKING_JOB_INTERVAL

logger = logging.getLogger(__name__)


def get_yaml_info():
    '''
    从gitee托管的开源软件组织中获取所有的开源软件仓库里的yaml文件的信息
    :return:
    '''
    ret_lst = list()
    repo_list = get_repo()

    for repo in repo_list:
        branch_list = get_branch(repo)
        for branch in branch_list:
            if 'patch-tracking' not in branch:
                ret_dict = dict()
                yaml_dict = get_yaml_content(repo, branch)
                ret_dict['scm_repo'] = yaml_dict['src_repo']
                ret_dict['scm_branch'] = yaml_dict['src_branch']
                ret_dict['repo'] = repo
                ret_dict['branch'] = branch
                if yaml_dict['patch_tracking_enabled'] == 'true':
                    ret_dict['enabled'] = True
                else:
                    ret_dict['enabled'] = False
                ret_lst.append(ret_dict)

    return ret_lst


def yaml_info_to_db(ret_lst):
    for item in ret_lst:
        data = Tracking.query.filter_by(repo=item['repo'], branch=item['branch']).first()
        if data:
            logger.debug('update tracking: %s', data)
            item['scm_commit'] = data.scm_commit
            update_tracking(item)
        else:
            github_api = GitHubApi()
            logger.debug('create tracking: %s', item)
            scm_commit = github_api.get_latest_commit(item['scm_repo'], item['scm_branch'])
            if scm_commit[0] == 'success':
                item['scm_commit'] = scm_commit[1]['latest_commit']
                create_tracking(item)
            else:
                logger.error('creating track db: %s failed.', scm_commit[1])


def yaml_to_db():
    ret_lst = get_yaml_info()
    yaml_info_to_db(ret_lst)


def add_job(job_id, func, args, seconds):
    """添加job"""
    logger.info("Add Tracking job - %s", job_id)
    scheduler.add_job(
        id=job_id,
        func=func,
        args=args,
        trigger='interval',
        seconds=seconds,
        misfire_grace_time=1200,
        next_run_time=datetime.datetime.now()
    )


def load(all_track):
    all_job_id = list()
    for item in scheduler.get_jobs():
        all_job_id.append(item.id)
    for track in all_track:
        if track.branch.split('/')[0] != 'patch-tracking':
            job_id = str(track.repo + ":" + track.branch)
            if job_id not in all_job_id:
                add_job(
                    job_id=job_id,
                    func='patch_tracking.task.task_apscheduler:single_upload_patch_to_gitee',
                    args=(track, ),
                    seconds=int(TRACKING_JOB_INTERVAL)
                )
